package com.example.orderservice.repository;

import com.example.orderservice.entity.OutboxEvent;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Outbox 事件仓库接口
 */
@Repository
public interface OutboxEventRepository extends JpaRepository<OutboxEvent, Long> {
    
    /**
     * 查找未处理的事件
     */
    @Query("SELECT e FROM OutboxEvent e WHERE e.processed = false AND e.retryCount < e.maxRetries ORDER BY e.createdAt ASC")
    List<OutboxEvent> findUnprocessedEvents();
    
    /**
     * 查找指定聚合的未处理事件
     */
    @Query("SELECT e FROM OutboxEvent e WHERE e.aggregateId = :aggregateId AND e.processed = false ORDER BY e.createdAt ASC")
    List<OutboxEvent> findUnprocessedEventsByAggregateId(@Param("aggregateId") String aggregateId);
    
    /**
     * 查找需要重试的事件（超过重试间隔时间）
     */
    @Query("SELECT e FROM OutboxEvent e WHERE e.processed = false AND e.retryCount < e.maxRetries AND e.createdAt < :retryBefore ORDER BY e.createdAt ASC")
    List<OutboxEvent> findEventsForRetry(@Param("retryBefore") LocalDateTime retryBefore);
}

